package com.bugman.managed;

import com.bugman.business.UserService;
import com.bugman.entity.User;
import java.io.IOException;
import java.security.Principal;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;

/**
 *
 * @author Flashman & Ediczech
 */
public class BaseBean {
    final protected String RESOURCE_BUNDLE = "messages";
    protected Logger logger;
    @EJB
    UserService userService;

    public BaseBean() {
        logger = Logger.getLogger(this.getClass());    
        logger.info("Vytvarim managed beanu " + this.getClass().getSimpleName());
    }

    protected ResourceBundle getBundle() {
        return ResourceBundle.getBundle(RESOURCE_BUNDLE, Locale.getDefault());
    }

    protected User getLoggedUser() {
        if (isUserLogged()) {
            return userService.getUser(getLoggedUserName());
        } else {
            return null;
        }
    }
        protected String getLoggedUserName() {
        if (isUserLogged()) {
            return getUserPrincipal().getName();
        } else {
            return null;
        }
    }

    protected boolean isUserLogged() {
        if (getUserPrincipal() != null) {
            return true;
        } else {
            return false;
        }
    }

    protected boolean isUserInRole(String role){
        return getServletRequest().isUserInRole(role);
    }

    protected String getRequestParameter(String parameter) {
        return getServletRequest().getParameter(parameter);
    }

    protected FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    protected HttpSession getSession() {
        return (HttpSession) getFacesContext().getExternalContext().getSession(true);
    }

    /* Metoda, ktera vraci HttpServletRequest aplikace a reprezentuje http pozadavek klienta */
    protected HttpServletRequest getServletRequest() {
        return (HttpServletRequest) getFacesContext().getExternalContext().getRequest();
    }

    protected HttpServletResponse getServletResponse() {
        return (HttpServletResponse) getFacesContext().getExternalContext().getResponse();
    }

    protected void redirect(String page) throws IOException {
        getServletResponse().sendRedirect(getServletRequest().getContextPath() + "/faces/" + page);
    }

    private Principal getUserPrincipal() {
        return getServletRequest().getUserPrincipal();
    }

}